<script>
import axios from "axios";
import { VueEditor } from "vue2-editor";

export default {
  name: "XiaoQuComponent",
  components: { VueEditor },
  data: () => ({}),
  data() {
    return {
      name: "",
      publicitytyext: "",
      createtime: "",
      pageNum: 1,
      pageSize: 10,
      total: 0,
      tableData: [], //表单数据对象

      value1: "",
      input: "",
      dialogFormVisible: false,
      dialogTitle: "", //对话框标题
      form: {
        id: "", //id
        name: "", //标题
        publicitytext: "", //富文本内容
        createtime: "", //创建时间
      },
      tableData: [],
      tableData2: [],
      addressAll: [], //省市区
      address: [], //你选择的地址
      formLabelWidth: "120px",
      //查看关联门店里的搜索数据
      association: false,
      checkBtn2: {
        villageName2: "",
        pageNum: 1,
        pageSize: 10,
      },
      addAssociation: false,
      checkBtn3: {
        villageName3: "",
      },
      //搜索框数据对象
      searchContent: {
        name: "",
        time: [],
        pageNum: 1,
        pageSize: 10,
        communityName: "",
      },
      xiaoquID: "",
      tableData3: [],
      row: {}, // 全局row 把scope.row赋给它
      allId: -1, //全局id用来在新增和修改是做判断
      page: {
        pageSize: 10, //默认每页显示10条
        currentPage: 1, //默认显示第一页
        total: 0, //总条数
      },
    };
  },
  //   页面初始化后执行
  created() {
    this.getAllProvinceAndCityList();
    // this.getAllXiaoqu();
    this.flushPage();
  },

  methods: {
    //获取省市
    getAllProvinceAndCityList() {
      // 获取全国所有省份和城市的列表
      var that = this;
      this.$http
        .get("https://restapi.amap.com/v3/config/district", {
          // 高德地图的API
          params: {
            key: "94214e26e4b0ec3a7d2ed9204f051583", // 这个是申请的 Key，读者自行写入
            keywords: "中国",
            subdistrict: 3,
            extensions: "base",
          },
        })
        .then((response) => {
          console.log(response.data);
          for (
            let i = 0;
            i < response.data.districts[0].districts.length;
            i++
          ) {
            let provinceMap = new Map();
            provinceMap.value = response.data.districts[0].districts[i].adcode; //区域编号
            provinceMap.label = response.data.districts[0].districts[i].name; //省名称
            provinceMap.children = [];
            that.addressAll.push(provinceMap); //添加省份
            for (
              let j = 0;
              j < response.data.districts[0].districts[i].districts.length;
              j++
            ) {
              let cityMap = new Map();
              cityMap.value =
                response.data.districts[0].districts[i].districts[j].adcode; //区域编号
              cityMap.label =
                response.data.districts[0].districts[i].districts[j].name; //市名称
              cityMap.children = [];
              provinceMap.children.push(cityMap); //添加市
              for (
                let k = 0;
                k <
                response.data.districts[0].districts[i].districts[j].districts
                  .length;
                k++
              ) {
                let areaMap = new Map();
                areaMap.value =
                  response.data.districts[0].districts[i].districts[
                    j
                  ].districts[k].adcode; //区域编号
                areaMap.label =
                  response.data.districts[0].districts[i].districts[
                    j
                  ].districts[k].name; //区县名称
                cityMap.children.push(areaMap); //添加区县
              }
            }
          }
        });
    },
    //获取经纬度
    latitude() {
      this.$http
        .get("https://restapi.amap.com/v3/geocode/geo?", {
          // 高德地图的API
          params: {
            key: "94214e26e4b0ec3a7d2ed9204f051583", // 这个是申请的 Key，读者自行写入
            address: this.address.join(""),
          },
        })
        .then((res) => {
          let rdata = res.data;
          let geo = rdata.geocodes[0];
          this.form.location = geo.location; //经纬度
          console.log(this.form.location);
          this.form.communityLongitude = this.form.location.split(",")[0];
          this.form.communityLatitude = this.form.location.split(",")[1];
        })
        .catch(() => {
          this.$message.error("请获取位置");
        });
    },
    // 添加删除
    save() {
      // 去除 HTML 标签的函数
      function stripHtmlTags(html) {
        const doc = new DOMParser().parseFromString(html, "text/html");
        return doc.body.textContent || "";
      }
      if (this.allId === -1) {
        //allId为空 新增
        this.dialogFormVisible = false;
        // 去除富文本内容中的 HTML 标签
        const plainText = stripHtmlTags(this.form.publicitytext);
        this.axios
          .post("/publicity/addNotice", {
            id: this.form.id,
            name: this.form.name,
            publicitytext: plainText,
            createtime: this.form.createtime,
          })
          .then((res) => {
            this.clearForm();
            this.flushPage();
          })
          .catch((err) => {
            console.log("请求失败");
          });
      } else {
        //allId不为空 修改
        this.dialogFormVisible = false;
        // 去除富文本内容中的 HTML 标签
        const plainText = stripHtmlTags(this.form.publicitytext);
        this.axios
          .put("/publicity/updateNotice", null, {
            params: {
              id: this.form.id,
              name: this.form.name,
              publicitytext: plainText,
              createtime: this.form.createtime,
            },
          })
          .then((res) => {
            console.log(res.data);
            this.clearForm();
            setTimeout(this.flushPage, 500);
          });
      }
    },
    //新增小区
    addXiaoqu() {
      this.dialogTitle = "新增公告";
      this.dialogFormVisible = true;
      this.clearForm();
      this.allId = -1;
    },
    //保存后清空表单
    clearForm() {
      this.form.id = "";
      this.form.name = "";
      this.form.createtime = "";
      this.form.publicitytext = "";
    },
    //格式化时间
    formatDateTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    //取消
    cancel() {
      this.dialogFormVisible = false;
    },
    //编辑小区
    editClick(row) {
      this.dialogTitle = "修改公告";
      this.dialogFormVisible = true;
      this.row = row;
      this.allId = this.row.id;
      console.log(this.allId);
      this.form.id = this.row.id;
      this.form.name = this.row.name;
      this.form.publicitytext = this.row.publicitytext;
      this.form.createtime = this.row.createtime;
    },
    // 日期格式化函数
    formatDate(dateValue) {
      // 检查输入值是否为空或无效
      if (dateValue == null || dateValue === "" || dateValue === undefined) {
        return null;
      }

      let date;
      // 如果输入是字符串，尝试解析
      if (typeof dateValue === "string") {
        // 如果已经是正确的格式，直接返回
        if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(dateValue)) {
          return dateValue;
        }
        // 否则尝试解析
        date = new Date(dateValue);
      } else if (dateValue instanceof Date) {
        date = dateValue;
      } else {
        // 如果不是字符串也不是Date对象，返回null
        return null;
      }

      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        console.warn("Invalid date:", dateValue);
        return null; // 如果日期无效，返回 null
      }

      // 格式化日期
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      const hours = date.getHours().toString().padStart(2, "0");
      const minutes = date.getMinutes().toString().padStart(2, "0");
      const seconds = date.getSeconds().toString().padStart(2, "0");

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    //刷新页面
    flushPage() {
      this.axios
        .get("/publicity/fetchAll", {
          params: {
            //传输的参数
            page: this.pageNum,
            size: this.pageSize,
          },
        })
        .then((res) => {
          console.log(res);
          this.tableData = res.data.data.list.map((item) => ({
            ...item,
            createtime: this.formatDate(item.createtime),
          }));
          //页面加载时添加总数量
          this.total = res.data.data.total;
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 分页
    handleSizeChange(size) {
      this.pageSize = size;
      // 可以在这里重新获取数据
      this.flushPage();
    },
    // 切换当前页
    handleCurrentChange(page) {
      console.log(page);
      this.pageNum = page;
      this.flushPage();
    },

    //删除小区
    deleteClick(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.axios
            .delete("/publicity/deleteNotice", {
              params: {
                id: id,
              },
            })
            .then((res) => {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.flushPage();
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //搜索
    searchClick() {
      if (!this.searchContent.time || !Array.isArray(this.searchContent.time)) {
        this.searchContent.time = [];
      }

      let params = {
        page: this.pageNum,
        size: this.pageSize,
        name: this.searchContent.name || null,
      };

      // 只有当时间数组存在且有值时才添加到参数中
      if (this.searchContent.time.length === 2) {
        const beginTime = this.formatDate(this.searchContent.time[0]);
        const endTime = this.formatDate(this.searchContent.time[1]);
        if (beginTime) params.begintime = beginTime;
        if (endTime) params.endtime = endTime;
      }

      console.log("Search params:", params); // 添加日志

      this.axios
        .get("/publicity/searchNotice", { params })
        .then((res) => {
          console.log(res);
          console.log(res.data.data.list);
          this.tableData = res.data.data.list;
          this.total = res.data.data.total; // 假设后端返回了总数
        })
        .catch((err) => {
          console.error("搜索失败:", err);
          this.$message.error("搜索失败，请重试");
        });
    },
    relativeShop(row) {
      this.association = true;
      this.axios
        .get("/communityShop", {
          params: {
            //点击关联门店时  获取对应的 小区id
            xiaoquID: row.communityId,
            page: 1,
            size: 10,
          },
        })
        .then((res) => {
          //res存储的说就是通过链接取得的数据；
          console.log(res.data.list);
          this.tableData2 = res.data.list;
          // console.log("-------" + this.tableData2)
        })
        .catch((err) => {
          console.log("如果请求失败，才会执行catch");
        });
    },
    //查看关联门店--->搜索按钮
    lookAssociation() {
      this.axios
        .get("/associationSearch", {
          params: {
            pageNum: 1,
            pageSize: 10,
            shopName: this.checkBtn2.villageName2,
          },
        })
        .then((res) => {
          //res存储的说就是通过链接取得的数据；
          this.tableData2 = res.data.list;
          console.log(this.tableData2);
        })
        .catch((err) => {
          console.log("如果请求失败，才会执行catch");
        });
    },
  },
};
</script>

<template>
  <div class="xiaoqu">
    <div class="title">公告管理</div>
    <div class="xiaoqu-content">
      <!-- 搜索 -->
      <div class="searchBox">
        <!-- 公告名称搜索 -->
        <div class="searchLi">
          <span class="xiaoquName">标题名称：</span>
          <input type="text" autocomplete="off" v-model="searchContent.name" />
        </div>
        <!-- 公告时间搜索 -->
        <div class="searchLi">
          <span>创建时间：</span>
          <el-date-picker
            v-model="searchContent.time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </div>
        <!-- 搜索按钮 -->
        <div class="searchBtn">
          <el-button type="primary" @click="searchClick">搜索</el-button>
        </div>
      </div>
      <!-- 新增公告 -->
      <div class="addXiaoquBtn">
        <el-button type="text" @click="addXiaoqu" class="addBtn"
          >新增公告</el-button
        >
        <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
          <el-form :model="form">
            <el-form-item label="标题：" :label-width="formLabelWidth">
              <el-input v-model="form.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="内容简介：" :label-width="formLabelWidth">
              <!-- 富文本 -->
              <vue-editor v-model="form.publicitytext" />
            </el-form-item>
            <el-form-item label="创建时间" :label-width="formLabelWidth">
              <el-input
                v-model="form.createtime"
                autocomplete="off"
                placeholder="yyyy-MM-dd HH:mm:ss"
              ></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button @click="save">保 存</el-button>
          </div>
        </el-dialog>
      </div>
      <!-- 表格内容 -->
      <div class="xiaoqu-table">
        <el-table
          :data="tableData"
          border
          :cell-style="{ 'text-align': 'center' }"
          :header-cell-style="{
            background: '#1890ff',
            color: '#ffffff',
            'text-align': 'center',
          }"
        >
          <el-table-column prop="name" label="标题"> </el-table-column>
          <el-table-column prop="publicitytext" label="内容简介">
          </el-table-column>
          <el-table-column prop="createtime" label="创建时间">
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="editClick(scope.row)" type="text" size="small"
                >修改公告</el-button
              >
              <el-button
                @click="deleteClick(scope.row.id)"
                type="text"
                size="small"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--分页按钮-->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[5, 10, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<style scoped>
.title {
  font-size: 40px;
  color: #ff69b4; /* 粉紫色 */
  font-family: "STXingkai", "KaiTi", "SimSun", serif; /* 使用艺术字体 */
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3); /* 添加阴影效果 */
  font-weight: bold;
  letter-spacing: 2px; /* 增加字间距 */
  text-align: center;
  padding: 10px;
  background: linear-gradient(45deg, #ff69b4, #da70d6); /* 渐变背景 */
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
.xiaoqu {
  height: 800px;
  /* background-color: hotpink; */
}
.xiaoqu-content {
  padding: 20px;
}
.searchBox {
  display: flex;
  justify-content: flex-start;
}
.searchLi {
  margin-right: 20px;
}
.addXiaoquBtn {
  margin-top: 20px;
}
input {
  height: 34px;
  outline: none;
  border: 1px solid #aaa;
  padding: 0 15px;
  border-radius: 5px;
}
input:hover {
  border: 1px solid #555555;
}
input:focus {
  border: 1px solid #409eff;
}
.addBtn {
  padding: 10px 20px;
  background-color: #409eff;
  color: whitesmoke;
  border: 1px solid #409eff;
}
.xiaoqu-table {
  margin-top: 20px;
  table-layout: auto;
}
</style>